<template>
  <div class="contract-score-page">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span class="page-title">合同评分</span>
          <div class="header-actions" v-if="isEdit">
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit" :loading="loading">提交评分</el-button>
          </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="合同信息" :column="2" border>
        <el-descriptions-item label="合同名称">
          {{ formData.contractName || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="负责人">
          {{ formData.majorUsername || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="设计师">
          {{ formData.designerName || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="评价状态">
          <el-tag :type="!isEdit ? 'success' : 'warning'">
            {{ !isEdit ? "已评价" : "未评价" }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider />

      <!-- 合同评分部分 -->
      <div class="score-section">
        <h4>合同总评</h4>
        <el-form ref="scoreFormRef" :model="formData" :rules="scoreRules" label-width="120px">
          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="合同得分" prop="contractScore">
                <el-rate v-model="formData.contractScore" :disabled="!isEdit"></el-rate>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="合同评价" prop="contractRemark">
                <el-input
                  v-if="isEdit"
                  v-model="formData.contractRemark"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入合同评价"
                  maxlength="200"
                  show-word-limit
                />
                <span v-else>{{ formData.contractRemark }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="设计得分" prop="designerScore">
                <el-rate v-model="formData.designerScore" :disabled="!isEdit"></el-rate>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="设计评价" prop="designerRemark">
                <el-input
                  v-if="isEdit"
                  v-model="formData.designerRemark"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入设计评价"
                  maxlength="200"
                  show-word-limit
                />
                <span v-else>{{ formData.designerRemark }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="8">
              <el-form-item label="负责人得分" prop="majorScore">
                <el-rate v-model="formData.majorScore" :disabled="!isEdit"></el-rate>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="负责人评价" prop="majorRemark">
                <el-input
                  v-if="isEdit"
                  v-model="formData.majorRemark"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入负责人评价"
                  maxlength="200"
                  show-word-limit
                />
                <span v-else>{{ formData.majorRemark }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <el-divider />

      <!-- 合同节点评分 -->
      <div class="node-score-section">
        <h4>合同节点评分</h4>

        <div
          v-for="(node, nodeIndex) in formData.contractNodeScoreVos"
          :key="nodeIndex"
          class="node-score-item"
        >
          <div class="node-header disf alc">
            <el-icon class="mr5"><Management /></el-icon>
            {{ node.nodeName }}
          </div>

          <div class="node-content">
            <el-form :model="node" :rules="nodeScoreRules" label-width="100px">
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="节点得分" prop="score">
                    <el-rate v-model="node.score" :disabled="!isEdit"></el-rate>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="节点评价" prop="remark">
                    <el-input
                      v-if="isEdit"
                      type="textarea"
                      class="mr15"
                      v-model="node.remark"
                      placeholder="请输入节点评价"
                    />
                    <span v-else>{{ node.remark }}</span>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <!-- 节点任务项及人员评分 -->
            <div class="user-score-section">
              <div class="sub-header">
                <h4>任务项及人员评分</h4>
              </div>

              <div
                v-for="(userScore, userIndex) in node.contractUserScores"
                :key="userIndex"
                class="user-score-item"
              >
                <p class="user-score-title">
                  {{ userScore.name }} • 「{{ userScore.username || "未知人员" }}」
                </p>
                <el-form label-width="90px">
                  <el-row :gutter="20">
                    <!-- 
                    <el-col :span="8">
                      <el-form-item label="任务名称">
                        {{ userScore.name }}
                      </el-form-item>
                    </el-col>
                    <el-col :span="16">
                      <el-form-item label="人员">
                        {{ userScore.username || "-" }}
                      </el-form-item>
                    </el-col>
                     -->
                    <el-col :span="8">
                      <el-form-item label="得分">
                        <el-rate v-model="userScore.score" :disabled="!isEdit"></el-rate>
                      </el-form-item>
                    </el-col>
                    <el-col :span="16">
                      <el-form-item label="评价">
                        <el-input v-if="isEdit" v-model="userScore.remark" placeholder="人员评价" />
                        <span v-else>{{ userScore.remark }}</span>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </div>
          </div>
        </div>

        <div v-if="formData.contractNodeScoreVos.length === 0" class="empty-node">
          <el-empty description="暂无节点评分数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from "element-plus";
import ContractScoreAPI, { type ContractScorePageVO } from "@/api/flow/contractScore.api";

defineOptions({
  name: "ContractScoreDetail",
  inheritAttrs: false,
});

const route = useRoute();
const router = useRouter();

const loading = ref(false);
const scoreFormRef = ref<FormInstance>();
const contractId = ref("");

// 表单数据
const formData = reactive<ContractScorePageVO>({
  contractId: contractId.value,
  contractNodeScoreVos: [],
});
const isEdit = computed(() => formData.status === 0);

// 验证规则
const scoreRules: FormRules = {
  contractScore: [{ required: true, message: "请输入合同得分", trigger: "blur" }],
  designerScore: [{ required: true, message: "请输入设计得分", trigger: "blur" }],
  majorScore: [{ required: true, message: "请输入负责人得分", trigger: "blur" }],
};

const nodeScoreRules: FormRules = {
  nodeName: [{ required: true, message: "请输入节点名称", trigger: "blur" }],
  score: [{ required: true, message: "请输入节点得分", trigger: "blur" }],
};

// 加载合同评分数据
const loadContractScore = async () => {
  try {
    loading.value = true;
    const response = await ContractScoreAPI.loadByContractId(contractId.value);
    if (response) {
      Object.assign(formData, response);
    }
  } catch (error) {
    console.error("加载合同评分数据失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 提交评分
const handleSubmit = async () => {
  if (!scoreFormRef.value) return;

  try {
    await scoreFormRef.value.validate();

    loading.value = true;
    const submitData = { ...formData };

    // 设置评价状态为已评价
    submitData.status = 1;

    await ContractScoreAPI.review(submitData);

    ElMessage.success("评分提交成功");
    loadContractScore();
  } catch (error) {
    console.error("提交评分失败:", error);
    ElMessage.error("提交评分失败");
  } finally {
    loading.value = false;
  }
};

// 取消
const handleCancel = () => {
  ElMessageBox.confirm("确定要取消评分吗？未保存的数据将会丢失。", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      router.back();
    })
    .catch(() => {
      // 用户取消操作
    });
};

// 初始化
onActivated(() => {
  if (!route.query.contractId) {
    ElMessage.error("合同ID不存在");
    router.back();
    return;
  }
  if (route.query.contractId == contractId.value) return;
  // id变动 重置数据
  contractId.value = route.query.contractId as string;
  loadContractScore();
});
</script>

<style scoped lang="scss">
.contract-score-page {
  padding: 20px;

  .page-card {
    min-height: calc(100vh - 40px);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .page-title {
      font-size: 18px;
      font-weight: 600;
    }
  }

  .score-section,
  .node-score-section {
    h4 {
      margin-bottom: 16px;
      color: #303133;
    }
  }

  .node-score-item {
    margin-bottom: 25px;
    background-color: #f7f7f7;
    border-radius: 10px;

    .node-header {
      padding: 10px;
      background-color: #e4e8f2;
      border-radius: 9px;
      // text-shadow: 1px 1px 2px #aaa;
      .el-icon {
        color: #606266;
      }
    }
    .node-content {
      padding-top: 10px;
    }
  }

  .user-score-section {
    padding: 0 16px 15px;
    border-radius: 4px;

    .sub-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 7px;

      h4 {
        margin: 0;
        color: #606266;
        font-size: 14px;
      }
    }

    .el-form-item {
      margin-bottom: 5px;
    }

    .user-score-item {
      margin-bottom: 12px;
      padding: 12px 12px 10px;
      background: white;
      border-radius: 4px;
      border: 1px solid #e4e7ed;

      .user-score-title {
        font-size: 14px;
        padding-bottom: 8px;
        margin-bottom: 10px;
        border-bottom: 1px dotted #e4e7ed;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .empty-node {
    text-align: center;
    padding: 40px 0;
  }
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-divider) {
  margin: 24px 0;
}
</style>
